<script setup>
import Login from "@/components/Login.vue";
import {inject, reactive, ref} from "vue";
import MpcUtil from "@/util/MpcUtil.js";
import {Burger, Microphone} from "@element-plus/icons-vue";

/**
 * 图像转Base64
 */
function getBase64Image(img) {
  const canvas = document.createElement("canvas");
  canvas.width = img.width;
  canvas.height = img.height;
  var ctx = canvas.getContext("2d");
  ctx.drawImage(img, 0, 0, img.width, img.height);
  var ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase();
  var dataURL = canvas.toDataURL("image/" + ext);
  return dataURL;
}
/**
 *Base64字符串转二进制
 */
function dataURLtoBlob(dataurl) {
  var arr = dataurl.split(','),
      mime = arr[0].match(/:(.*?);/)[1],
      bstr = atob(arr[1]),
      n = bstr.length,
      u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], {
    type: mime
  });
}



let chunks = [];
if (navigator.mediaDevices.getUserMedia) {
  const constraints = { audio: true };
  navigator.mediaDevices.getUserMedia(constraints).then(
      stream => {
        console.log("授权成功！");
        const recordBtn = document.querySelector(".record-btn");
        const mediaRecorder = new MediaRecorder(stream);
        mediaRecorder.ondataavailable = function(e) {
          chunks.push(e.data);
          var audio = document.getElementById("audio");
          console.log(">>"+window.URL.createObjectURL(chunks[chunks.length - 1]));
          audio.src = window.URL.createObjectURL(chunks[chunks.length - 1]);
          console.log(chunks[chunks.length - 1])
        };
        recordBtn.onclick = () => {
          if (mediaRecorder.state === "recording") {
            mediaRecorder.stop();
            recordBtn.textContent = "开始录音";
            console.log("录音结束");
            console.log(chunks)
          } else {
            mediaRecorder.start();
            console.log("录音中...");
            recordBtn.textContent = "停止录音";
          }
          console.log("录音器状态：", mediaRecorder.state);
        };
      },
      () => {
        console.error("授权失败！");
      }
  );
} else {
  console.error("浏览器不支持 getUserMedia");
}

function connect() {
  MpcUtil.connect('ws://localhost:5219', ()=>{
    MpcUtil.sendPath("/group");
      }, (res)=>{
    switch (res.type) {
      case 51: {
        messageList.push({
          type: 51,
          fromId: res.fromId,
          toType: res.toType,
          toId: res.toId,
          content: res.content
        });
        break;
      }
      case 53: {
        const groups = res.data;
        for(let i in groups) {
          items.push({
            toType: 3,
            tag: '群组',
            id: groups[i].id,
            name: groups[i].name
          })
        }
        break;
      }
      case 54: {
        const buffer = MpcUtil.mergeAudioResponse(res);
        if (buffer !== undefined) {
          const blob = new Blob([buffer], {type: "audio/webm;codecs=opus"});
          messageList.push({
            type: 54,
            fromId: res.fromId,
            toType: res.toType,
            toId: res.toId,
            src: window.URL.createObjectURL(blob)
          });
        }
        break;
      }
      case 55: {
        const buffer = MpcUtil.mergeAudioResponse(res);
        if (buffer !== undefined) {
          const blob = new Blob([buffer], {type: "image/png;codecs=opus"});
          messageList.push({
            type: 55,
            fromId: res.fromId,
            toType: res.toType,
            toId: res.toId,
            src: window.URL.createObjectURL(blob)
          });
        }
        break;
      }
      default: {
        console.log("未知响应类型！");
      }
    }
  });
}

function sendChat() {
  const text = document.getElementById("chatContent").value;
  MpcUtil.sendChat(item.toType, item.id, text===''?"Hello MPC !":text);
}

function sendAudio() {
  MpcUtil.sendAudio(item.toType, item.id, chunks[chunks.length - 1]);
}

function sendPic() {
  const img = "/test_pic.png";
  const image = new Image();
  image.src = img;
  image.onload = function() {
    //文件的Base64字符串
    const base64 = getBase64Image(image);
    // console.log(base64);
    //Base64字符串转二进制
    const file = dataURLtoBlob(base64);
    // console.log(file);
    MpcUtil.sendPic(item.toType, item.id, file);
  }
}

/**
 * 加入聊天室
 * @param chatRoomId 聊天室ID
 */
function joinChatRoom(chatRoomId) {
  MpcUtil.sendPath("/chatroom/join", [chatRoomId], (res)=>{
    if (res.data>=1) {
      const joinChatRoomBtn = document.getElementById("joinChatRoom");
      joinChatRoomBtn.disabled = true;
      joinChatRoomBtn.textContent = "加入成功！";
    }
  });
}

const items = reactive([
  {
    toType: 5,
    tag: '聊天室',
    id: '1',
    name: '家人们聊天室'
  },
  {
    toType: 1,
    tag: '个人',
    id: 'admin',
    name: 'admin'
  },
  {
    toType: 1,
    tag: '个人',
    id: 'lisi',
    name: 'lisi'
  }
]);
// 通讯录选中项
const selectedItemsIndex = ref(0);
let item = items[selectedItemsIndex.value];
// 消息列表
const messageList = reactive([]);
// 选中操作
function selectItem(index) {
  selectedItemsIndex.value = index;
  item = items[index];
}

</script>
<template>
<!--            <el-icon size="35" @click="sendPic()"><Picture /></el-icon>-->
<!--            <div>图片</div>-->
<!--            <el-icon size="35" @click="sendAudio()"><Microphone /></el-icon>-->
<!--            <div>语音</div>-->

  <table style="width: 100vw; height: 100vh; margin: 0; border: 0; padding: 0;">
    <thead>
      <tr>
        <td style="width: 20%; height: 60px; line-height: 60px; text-align: center; background-color: rgb(100,180,250)">通讯录</td>
        <td style="background-color: rgb(252,252,252); border-bottom: 1px solid rgb(220,220,220);">{{items[selectedItemsIndex].name}}</td>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td style="border-right: 1px solid rgb(180,180,180);">
          <div style="height: 100%; width: 100%; background-color: rgb(250,250,251);">
            <div v-for="(item, i) in items" class="leftUser" :class="selectedItemsIndex===i?'leftUser_click':''" @click="selectItem(i)">
              {{item.name}}
              <span style="border: 1px solid rgb(200,200,200); border-radius: 6px; padding: 1px 3px">{{item.tag}}</span>
            </div>
            <Login style="width: calc(100% - 10px);" :connect="connect"></Login>
            <button id="joinChatRoom" style="height: 60px; width: 100%;" @click="joinChatRoom('1')">加入 -> 家人们聊天室</button>
          </div>
        </td>
        <td>
          <div style="height: 100%; width: 100%; background-color: rgb(250,250,253)">
            <div style="height: calc(100vh - 125px); width: 100%; overflow-x: hidden; overflow-y: scroll;">
              <div v-for="message in messageList" class="message">
                <div class="message_title">{{message.fromId}}&ensp;->&ensp;{{message.toId}}&ensp;|&ensp;{{message.toType===1?'个人':'群组'}}</div>
                <span class="message_text" v-if="message.type===51">{{message.content}}</span>
                <audio class="message_audio" v-else-if="message.type===54" :src="message.src" style="width: 300px;" controls></audio>
                <img v-else-if="message.type===55" :src="message.src" style="width: 300px; border-radius: 10px" alt="">
              </div>
            </div>
            <div class="inputBox">
              <audio id="audio" style="width: 20%; float: left;" controls></audio>
              <button class="record-btn" style="width: 8%; height: 100%; float: left;">开始录音</button>
              <button style="width: 8%; height: 100%; float: left;" @click="sendAudio()">发送语音</button>
              <el-icon size="35" @click="sendPic()" style="float: left; height: 100%; width: 50px; margin: 0;"><Picture /></el-icon>
              <input id="chatContent" type="text" style="float: left; width: 10%; height: 100%">
              <button style="width: 8%; height: 100%; float: left;" @click="sendChat()">发送文字</button>
            </div>
          </div>
        </td>
      </tr>
    </tbody>
  </table>
</template>
<style scoped>
.box {
  background-color: rgba(250,250,253,1);
  width: 400px;
  margin: 10px auto;
  padding: 10px;
  box-shadow: 0 0 8px 0 rgba(180,180,180,1);
  border-radius: 10px;
  transition: all ease-out 0.2s;
  float: left;
}
.box:hover {
  box-shadow: 0 0 10px 0 rgba(150,150,150,1);
}


.messages {
  width: 100%;
  min-height: 100px;
  box-shadow: inset 0 0 5px 0 rgba(180,180,180,1);
  border-radius: 10px;
}


button {
  border: 1px rgba(1,1,1,1) solid;
  border-radius: 10px;
}
button:hover {
  background-color: rgba(245,245,249,1);
}
button:active {
  background-color: rgba(230,230,234,1);
}

td .el-icon {
  background-color: rgba(247,247,255,1);
  color: rgba(50,50,50,1);
  border-radius: 5px;
  padding: 3px;
  box-shadow: 0 0 0 1px rgba(100,100,100,1);
  margin-top: 10px;
  margin-right: 10px;
}
td .el-icon:hover {
  background-color: rgba(230,230,238,1);
}
td .el-icon:active {
  background-color: rgba(180,180,188,1);
}

td div {
  text-align: center;
  width: 35px;
  margin-right: 10px;
  user-select: none;
  height: 12px;
  line-height: 12px;
  font-size: 12px;
}

.leftUser {
  width: 100%;
  height: 50px;
  line-height: 50px;
}
.leftUser:hover {
  background-color: rgb(230,230,230);
}
.leftUser_click {
  background-color: rgb(240,240,240);
}

.rightBox {
  width: 100%;
  height: 100%;
}

.inputBox {
  background-color: rgb(245,245,245);
  width: 100%;
  height: 50px;
  border-top: 1px solid rgb(200,200,200);
}

.message {
  width: 100%;
  height: auto;
  margin: 5px;
  text-align: left;
}
.message_title {
  line-height: 20px;
  height: 20px;
  width: 100%;
  text-align: left;
  margin: 0 0 5px 0;
}
.message_text {
  border-radius: 5px;
  background-color: rgb(220,220,220);
  box-shadow: 0 0 0 1px rgb(200,200,200);
  padding: 2px 8px;
  line-height: 20px;
}
.message_audio {
}
</style>
